package com.wy.projectssj.service.impl;

import com.wy.projectssj.dao.RoleDao;
import com.wy.projectssj.dao.UserDao;
import com.wy.projectssj.dao.UserRoleDao;
import com.wy.projectssj.domain.PageBean;
import com.wy.projectssj.domain.Role;
import com.wy.projectssj.domain.User;
import com.wy.projectssj.service.UserService;
import com.wy.projectssj.utils.Uuid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: wy
 * @Date:2019/8/28 21:07
 */
    @Service
public class UserServiceImpl implements UserService {
      @Autowired
     private UserDao userDao;
      @Autowired
      private UserRoleDao userRoleDao;
      @Autowired
      private RoleDao roleDao;


    @Override
    public PageBean<User> findAll(Integer rows, Integer currentPage ) {
           PageBean<User> pb=new PageBean<>();
            //总记录数
            Integer totalCount=userDao.findAll();
            //页面总数
            Integer totalPage=totalCount%rows==0?totalCount/rows:totalCount/rows+1;
             //起始索引
              Integer start=(currentPage-1)*rows;
              List<User> list = userDao.findByCondition(start, rows);
              pb.setCurrentPage(currentPage);
              pb.setList(list);
              pb.setRows(rows);
               pb.setTotalCount(totalCount);
               pb.setTotalPage(totalPage);
        return pb;
    }

    @Override
    public int save(User user) {
         user.setId( Uuid.getUuid());
        return userDao.save(user);
    }

    @Override
    public int deleteUser(String[] ids) {
        /*在删除主表信息之前,先把中间表关联的信息删除*/
         int result=-1;
        if(ids!=null&&ids.length>0) {
               userRoleDao.deleteByIds(ids);
            result =  userDao.delete(ids);
        }
        return  result;
    }

    @Override
    public User findById( String id) {
             //查到所有Role的集合
        List<Role> roleList = roleDao.findById(id);
        User user = userDao.findById(id);
        user.setRoles(roleList);
        return  user;
    }

    @Override
    public User login(User user) {

        return  userDao.findOne(user);
    }
}
